<!-- 引入 API 封装 -->
<!-- <script src="{{ asset('js/api.js') }}"></script> -->
<!-- <script src="{{ asset('js/store-api.js') }}"></script> -->

<div id="storelist">
    <el-container>
        <el-main>
            <!-- 搜索筛选区域 -->
            <el-card class="mb-4">
                <div slot="header">
                    <span><i class="el-icon-search"></i> 搜索筛选</span>
                </div>
                <el-form :model="searchForm" class="search-form">
                    <!-- 第一行 -->
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item label="门店名称">
                                <el-input v-model="searchForm.store_name" placeholder="请输入门店名称" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="门店申请人ID">
                                <el-input v-model="searchForm.uid" placeholder="请输入申请人ID" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="申请人信息">
                                <el-input v-model="searchForm.applicant_info" placeholder="姓名/昵称/手机号" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <!-- 第二行 -->
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item label="门店所在省">
                                <el-select v-model="searchForm.province_id" placeholder="选择省" clearable @change="onProvinceChange" style="width: 100%;">
                                    <el-option v-for="province in provinces" :key="province.id" :label="province.name" :value="province.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="门店所在市">
                                <el-select v-model="searchForm.city_id" placeholder="选择市" clearable @change="onCityChange" style="width: 100%;">
                                    <el-option v-for="city in cities" :key="city.id" :label="city.name" :value="city.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="门店所在区县">
                                <el-select v-model="searchForm.district_id" placeholder="选择区县" clearable style="width: 100%;">
                                    <el-option v-for="district in districts" :key="district.id" :label="district.name" :value="district.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <!-- 第三行 -->
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item label="入驻时间">
                                <el-date-picker
                                    v-model="searchForm.date_range"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%;">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" style="margin-top:40px">
                            <el-form-item label="黑名单">
                                <el-radio-group v-model="searchForm.is_black">
                                    <el-radio :label="0">否</el-radio>
                                    <el-radio :label="1">是</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" style="margin-top:40px">
                            <el-form-item label="">
                                <div style="display: flex; gap: 10px;">
                                    <el-button type="primary" @click="handleSearch" icon="el-icon-search">查询</el-button>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>

            <!-- 门店列表 -->
            <el-card>
                <div slot="header">
                    <span><i class="el-icon-shop"></i> 门店清单</span>
                    <span class="text-muted ml-2">共 @{{ pagination.total }} 家门店</span>
                </div>
                
                <el-table :data="list" v-loading="loading" stripe style="width: 100%">
                    <el-table-column prop="id" label="店家ID" width="80" sortable>
                        <template slot-scope="scope">
                            <strong>@{{scope.row.id}}</strong>
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="门店名称" width="250">
                        <template slot-scope="scope">
                            <div class="store-info">
                                <div class="store-thumb">
                                    <img :src="scope.row.thumb || '/images/default-store.png'" :alt="scope.row.store_name" class="store-image">
                                </div>
                                <div class="store-details">
                                    <div class="store-name">@{{ scope.row.store_name || '未设置' }}</div>
                                    <div class="store-address text-muted">@{{ scope.row.full_address || scope.row.address || '-' }}</div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="申请人" width="150">
                        <template slot-scope="scope">
                            <div class="applicant-info">
                                <el-avatar :src="scope.row.owner.avatar" :size="32" class="mr-2">
                                    @{{ scope.row.owner.name.charAt(0) }}
                                </el-avatar>
                                <div class="info-text">
                                    <div class="name">@{{ scope.row.owner.name }}</div>
                                    <div class="id text-muted">@{{ scope.row.owner.id }}</div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="门店分类" width="120">
                        <template slot-scope="scope">
                            <span>@{{ scope.row.category_name || (categoryNameMap[scope.row.category_id] || '未分类') }}</span>
                        </template>
                    </el-table-column>
                    
                    <el-table-column prop="mobile" label="门店电话" width="120">
                        <template slot-scope="scope">
                            <div>@{{ scope.row.mobile || '-' }}</div>
                        </template>
                    </el-table-column>
                    
                    <el-table-column prop="created_at" label="入驻时间" width="120"></el-table-column>
                    
                    <el-table-column label="到期时间" width="120">
                        <template slot-scope="scope">
                            <div>@{{ scope.row.validity_text || '无限期' }}</div>
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="是否推荐" width="100">
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.is_recommend"
                                :active-value="1"
                                :inactive-value="0"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                @change="toggleRecommend(scope.row)">
                            </el-switch>
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="收银台二维码" width="150">
                        <template slot-scope="scope">
                            <div class="qr-code-actions">
                                <el-button type="text" @click="viewQRCode(scope.row, 'collect_money_url')" size="mini">查看</el-button>
                                <el-button type="text" @click="downloadQRCode(scope.row, 'collect_money_url')" size="mini">下载</el-button>
                            </div>
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="操作" width="100" fixed="right">
                        <template slot-scope="scope">
                            <el-dropdown @command="handleCommand" trigger="click">
                                <el-button type="text" size="mini">
                                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                                </el-button>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item :command="{action: 'detail', id: scope.row.id}">
                                        <i class="el-icon-info"></i> 门店信息
                                    </el-dropdown-item>
                                    <el-dropdown-item :command="{action: 'password', id: scope.row.id}">
                                        <i class="el-icon-key"></i> 修改密码
                                    </el-dropdown-item>
                                    <el-dropdown-item :command="{action: 'blacklist', id: scope.row.id, current: scope.row.is_black}" :divided="true">
                                        <i class="el-icon-warning"></i> @{{ scope.row.is_black ? '移出黑名单' : '加入黑名单' }}
                                    </el-dropdown-item>
                                    <el-dropdown-item :command="{action: 'clerks', id: scope.row.id}">
                                        <i class="el-icon-user"></i> 核销员清单
                                    </el-dropdown-item>
                                    <el-dropdown-item :command="{action: 'group', id: scope.row.id}">
                                        <i class="el-icon-s-operation"></i> 置换分组
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </template>
                    </el-table-column>
                </el-table>
                
                <!-- 分页 -->
                <div class="pagination-wrapper mt-3" v-if="pagination.total > 0">
                    <el-pagination
                        @current-change="handleCurrentChange"
                        :current-page="pagination.page"
                        :page-size="pagination.pageSize"
                        layout="total, prev, pager, next, jumper"
                        :total="pagination.total">
                    </el-pagination>
                </div>
            </el-card>
        </el-main>
    </el-container>

    <!-- 门店详情弹窗 -->
    <el-dialog title="门店详情" :visible.sync="detailDialogVisible" width="1000px" :close-on-click-modal="false">
        <div v-loading="detailLoading">
            <el-form :model="detailForm" :rules="detailRules" ref="detailFormRef" label-width="120px" v-if="detailData">
                <!-- 基础信息 -->
                <el-card class="mb-3">
                    <div slot="header">
                        <span><i class="el-icon-user"></i> 基础信息</span>
                    </div>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="门店名称" prop="store_name" required>
                                <el-input v-model="detailForm.store_name" placeholder="请输入门店名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="经营状态" prop="operating_state" required>
                                <el-radio-group v-model="detailForm.operating_state">
                                    <el-radio :label="0">正常</el-radio>
                                    <el-radio :label="1">停用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="门店分类" prop="category_id" required>
                                <el-select v-model="detailForm.category_id" placeholder="请选择门店分类" style="width: 100%">
                                    <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="门店logo">
                                <el-upload
                                    class="avatar-uploader"
                                    :action="uploadUrl"
                                    :show-file-list="false"
                                    :on-success="handleLogoSuccess"
                                    :before-upload="beforeAvatarUpload"
                                    :http-request="handleImageUploadRequest">
                                    <i class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                                <div v-if="detailForm.thumb" class="image-preview-list mt-1">
                                    <el-image
                                        class="avatar is-clickable"
                                        :src="detailForm.thumb"
                                        :preview-src-list="[detailForm.thumb]"
                                        fit="cover"
                                    ></el-image>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="资质图片">
                        <el-upload
                            :action="uploadUrl"
                            list-type="picture-card"
                            :file-list="aptitudeFileList"
                            :on-success="handleAptitudeSuccess"
                            :on-remove="handleAptitudeRemove"
                            :before-upload="beforeAvatarUpload"
                            :http-request="handleImageUploadRequest">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <div v-if="aptitudePreviewList.length" class="image-preview-list mt-2">
                            <el-image
                                v-for="(img, index) in aptitudePreviewList"
                                :key="img"
                                class="preview-thumbnail"
                                :src="img"
                                :preview-src-list="aptitudePreviewList"
                                :initial-index="index"
                                fit="cover"
                            ></el-image>
                        </div>
                    </el-form-item>
                </el-card>

                <!-- 位置信息 -->
                <el-card class="mb-3">
                    <div slot="header">
                        <span><i class="el-icon-location"></i> 位置信息</span>
                    </div>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="省份" prop="province_id" required>
                                <el-select v-model="detailForm.province_id" placeholder="请选择省份" style="width: 100%" @change="onProvinceChange2">
                                    <el-option v-for="item in provinceOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="城市" prop="city_id" required>
                                <el-select v-model="detailForm.city_id" placeholder="请选择城市" style="width: 100%" @change="onCityChange2">
                                    <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="区县" prop="district_id" required>
                                <el-select v-model="detailForm.district_id" placeholder="请选择区县" style="width: 100%">
                                    <el-option v-for="item in districtOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="详细地址" prop="address" required>
                        <el-input v-model="detailForm.address" placeholder="请输入详细地址"></el-input>
                    </el-form-item>
                    <el-row :gutter="20">
                        <el-col :span="10">
                            <el-form-item label="经度">
                                <el-input-number v-model="detailForm.longitude" :precision="6" :step="0.000001" placeholder="经度" style="width: 100%"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="纬度">
                                <el-input-number v-model="detailForm.latitude" :precision="6" :step="0.000001" placeholder="纬度" style="width: 100%"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" style="display:flex;align-items:center;">
                            <el-button type="primary" @click="openMapPicker">选择坐标</el-button>
                        </el-col>
                    </el-row>
                </el-card>

                <!-- 联系方式 -->
                <el-card class="mb-3">
                    <div slot="header">
                        <span><i class="el-icon-phone"></i> 联系方式</span>
                    </div>
                    <el-form-item label="店铺电话" prop="mobile" required>
                        <el-input v-model="detailForm.mobile" placeholder="请输入店铺电话"></el-input>
                    </el-form-item>
                    <el-form-item label="门店介绍" prop="store_introduce" required>
                        <el-input type="textarea" v-model="detailForm.store_introduce" :rows="4" placeholder="请输入门店介绍"></el-input>
                    </el-form-item>
                </el-card>

                <!-- 营业信息 -->
                <el-card class="mb-3">
                    <div slot="header">
                        <span><i class="el-icon-time"></i> 营业信息</span>
                    </div>
                    <el-form-item label="营业时间" prop="business_hours">
                        <el-row :gutter="10">
                            <el-col :span="11">
                                <el-time-picker v-model="detailForm.business_hours_start" format="HH:mm" value-format="HH:mm" placeholder="开始时间" style="width: 100%"></el-time-picker>
                            </el-col>
                            <el-col :span="2" style="text-align: center; line-height: 40px;">
                                <span>至</span>
                            </el-col>
                            <el-col :span="11">
                                <el-time-picker v-model="detailForm.business_hours_end" format="HH:mm" value-format="HH:mm" placeholder="结束时间" style="width: 100%"></el-time-picker>
                            </el-col>
                        </el-row>
                    </el-form-item>
                </el-card>

                <!-- 管理人员信息 -->
                <el-card class="mb-3">
                    <div slot="header">
                        <span><i class="el-icon-user-solid"></i> 管理人员信息</span>
                    </div>
                    <el-form-item label="门店店长" prop="uid" required>
                        <div class="manager-info" v-if="detailForm.manager_info">
                            <div class="manager-avatar">
                                <el-avatar :size="40" :src="detailForm.manager_info.avatar" icon="el-icon-user-solid"></el-avatar>
                            </div>
                            <div class="manager-details">
                                <div class="manager-name">@{{ detailForm.manager_info.name }}</div>
                                <div class="manager-id">ID: @{{ detailForm.manager_info.id }}</div>
                            </div>
                            <div class="manager-actions">
                                <el-button type="text" @click="openManagerDialog">重新选择</el-button>
                                <el-button type="text" @click="clearManager">清空店长</el-button>
                            </div>
                        </div>
                        <div v-else class="no-manager">
                            <el-button type="primary" @click="openManagerDialog">选择店长</el-button>
                        </div>
                    </el-form-item>
                    <el-form-item label="门店推荐人ID">
                        <el-input v-model="detailForm.recruiter_id" placeholder="请输入推荐人ID"></el-input>
                    </el-form-item>
                </el-card>

                <!-- 账号信息 -->
                <el-card class="mb-3">
                    <div slot="header">
                        <span><i class="el-icon-key"></i> 账号信息</span>
                    </div>
                    <el-form-item label="登录账号">
                        <el-input v-model="detailForm.username" readonly>
                            <template slot="prepend">
                                <i class="el-icon-phone"></i>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="登录密码" required>
                        <div class="password-info">
                            <span class="password-mask">••••••••</span>
                            <el-button type="text" @click="showPasswordDialog2">修改密码</el-button>
                        </div>
                    </el-form-item>
                </el-card>
            </el-form>
        </div>
        
        <div slot="footer" class="dialog-footer">
            <el-button @click="detailDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveStoreDetail" :loading="saveLoading">保存</el-button>
        </div>
    </el-dialog>

    <!-- 店长选择弹窗 -->
    <el-dialog title="选择门店店长" :visible.sync="managerDialogVisible" width="720px">
        <div style="margin-bottom:10px; display:flex; gap:8px; align-items:center;">
            <el-input v-model="managerKeyword" placeholder="输入ID/昵称/姓名/手机号" clearable style="flex:1"></el-input>
            <el-button type="primary" @click="searchManagers">搜索</el-button>
        </div>
        <el-table :data="managerList" height="360" v-loading="managerLoading">
            <el-table-column prop="uid" label="UID" width="100"></el-table-column>
            <el-table-column label="会员" min-width="220">
                <template slot-scope="scope">
                    <div style="display:flex; align-items:center; gap:8px;">
                        <el-avatar :src="scope.row.avatar" :size="32"></el-avatar>
                        <div>
                            <div>@{{ scope.row.name || scope.row.nickname }}</div>
                            <div class="text-muted" style="font-size:12px;">@{{ scope.row.mobile }}</div>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="chooseManager(scope.row)">选择</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button @click="managerDialogVisible=false">关闭</el-button>
        </div>
    </el-dialog>

    <!-- 地图选择坐标弹窗 -->
    <el-dialog title="选择坐标" :visible.sync="mapDialogVisible" width="60%">
        <div style="margin-bottom:10px;display:flex;gap:8px;align-items:center;">
            <el-input v-model="mapKeyword" placeholder="输入地点检索" style="flex:1"></el-input>
            <el-button type="primary" @click="searchMap">搜索</el-button>
        </div>
        <div ref="mapContainer" style="width:100%;height:450px;border:1px solid #ebeef5;"></div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="mapDialogVisible=false">取消</el-button>
            <el-button type="primary" @click="confirmMapPoint">确定</el-button>
        </div>
    </el-dialog>

    <!-- 二维码查看弹窗 -->
    <el-dialog title="二维码查看" :visible.sync="qrCodeDialogVisible" width="400px">
        <div class="text-center">
            <img :src="currentQRCode" style="max-width: 100%; max-height: 300px;" v-if="currentQRCode">
            <div v-else class="text-muted">暂无二维码</div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="qrCodeDialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="downloadCurrentQRCode" v-if="currentQRCode">下载</el-button>
        </div>
    </el-dialog>
    
    <!-- 修改密码弹窗 -->
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="500px" :close-on-click-modal="false">
        <el-form :model="passwordForm" label-width="100px">
            <el-form-item label="新密码" required>
                <el-input v-model="passwordForm.new_password" type="password" placeholder="请输入新密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" required>
                <el-input v-model="passwordForm.confirm_password" type="password" placeholder="请再次输入新密码" show-password></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="passwordDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="updatePassword" :loading="passwordLoading">确定</el-button>
        </div>
    </el-dialog>
    
    <!-- 核销员清单弹窗 -->
    <el-dialog title="核销员清单" :visible.sync="clerksDialogVisible" width="900px">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="clerksSearchForm" class="demo-form-inline" style="margin-bottom: 20px;">
            <el-form-item label="核销员ID">
                <el-input v-model="clerksSearchForm.clerk_id" placeholder="请输入核销员ID" clearable style="width: 150px;"></el-input>
            </el-form-item>
            <el-form-item label="姓名">
                <el-input v-model="clerksSearchForm.realname" placeholder="请输入姓名" clearable style="width: 150px;"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
                <el-input v-model="clerksSearchForm.mobile" placeholder="请输入手机号" clearable style="width: 150px;"></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="clerksSearchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="启用" value="10"></el-option>
                    <el-option label="停用" value="20"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchClerks">搜索</el-button>
                <el-button @click="resetClerksSearch">重置</el-button>
            </el-form-item>
        </el-form>
        
        <div v-loading="clerksLoading">
            <el-table :data="clerksList" stripe style="width: 100%">
                 <el-table-column prop="id" label="核销员ID" width="100"></el-table-column>
                 <el-table-column label="姓名" width="180">
                     <template slot-scope="scope">
                         <div style="display:flex; align-items:center; gap:8px;">
                             <el-avatar :src="scope.row.avatar" :size="28">
                                 @{{ (scope.row.nickname || scope.row.realname || '-') .charAt(0) }}
                             </el-avatar>
                             <div style="display:flex; flex-direction:column;">
                                 <span>@{{ scope.row.nickname || scope.row.realname || '-' }}</span>
                                 <small style="color:#999;">UID: @{{ scope.row.uid || scope.row.id }}</small>
                             </div>
                         </div>
                     </template>
                 </el-table-column>
                 <el-table-column prop="mobile" label="手机号" width="130"></el-table-column>
                 <el-table-column prop="status" label="状态" width="100">
                     <template slot-scope="scope">
                         <el-tag :type="scope.row.status === 10 ? 'success' : 'danger'" size="small">
                             @{{ scope.row.status == 10 ? '正常' : '停用' }}
                         </el-tag>
                     </template>
                 </el-table-column>
                 <el-table-column label="核销记录" width="100">
                     <template slot-scope="scope">
                         <span>@{{ scope.row.verification_count || 0 }}</span>
                     </template>
                 </el-table-column>
                 <el-table-column prop="created_at" label="创建时间" width="160">
                     <template slot-scope="scope">
                         <span>@{{ scope.row.created_at ? scope.row.created_at : '-' }}</span>
                     </template>
                 </el-table-column>
                 <el-table-column label="操作" width="120">
                     <template slot-scope="scope">
                         <el-button size="mini" :type="scope.row.status === 10 ? 'danger' : 'success'" @click="toggleClerkStatus(scope.row)">
                             @{{ scope.row.status == 10 ? '停用' : '启用' }}
                         </el-button>
                     </template>
                 </el-table-column>
             </el-table>
            <div v-if="clerksList.length === 0 && !clerksLoading" class="text-center text-muted py-4">
                暂无核销员数据
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="clerksDialogVisible = false">关闭</el-button>
        </div>
    </el-dialog>
    
    <!-- 置换分组弹窗 -->
    <el-dialog title="置换分组" :visible.sync="switchGroupsDialogVisible" width="800px" :close-on-click-modal="false">
        <div v-loading="switchGroupsLoading">
            <el-form label-width="100px">
                <el-form-item label="选择置换分组">
                    <el-select v-model="selectedSwitchGroupId" placeholder="请选择置换分组" style="width: 100%;" @change="onSwitchGroupChange">
                        <el-option v-for="group in switchGroups" :key="group.id" :label="group.name" :value="group.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            
            <!-- 分组属性列表 -->
            <div v-if="selectedSwitchGroupId && groupProperties.length > 0" style="margin-top: 20px;">
                <h4>置换属性</h4>
                <el-table :data="groupProperties" border style="width: 90%; margin-top: 10px;">
                    <el-table-column prop="in_type_name" label="选择置换" width="200"></el-table-column>
                    <el-table-column prop="switch_code_name" label="置换转让" width="150"></el-table-column>
                    <el-table-column label="置换比例%" width="150">
                        <template slot-scope="scope">
                            <el-input-number 
                                v-model="scope.row.settlement_num" 
                                :min="0" 
                                :max="100" 
                                :precision="2"
                                size="small"
                                style="width: 120px;">
                            </el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="是否开启" width="">
                        <template slot-scope="scope">
                            <el-switch 
                                v-model="scope.row.is_enabled"
                                active-color="#13ce66"
                                inactive-color="#ff4949">
                            </el-switch>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            
            <div v-else-if="selectedSwitchGroupId" style="margin-top: 20px; text-align: center; color: #909399;">
                该分组暂无置换属性
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="switchGroupsDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveSwitchGroupSettings" :disabled="!selectedSwitchGroupId">保存</el-button>
        </div>
    </el-dialog>

</div>
<!-- <script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=b6WWqwPeGhsb9Wg7Sdvyf8vUOIGf3579"></script> -->
<script>
new Vue({
    el: '#storelist',
    data() {
        return {
            loading: false,
            pagination: { page: 1, pageSize: 10, total: 0 },
            searchForm: {
                store_name: '',
                uid: '',
                applicant_info: '',
                province_id: '',
                city_id: '',
                district_id: '',
                date_range: [],
                is_black: 0
            },
            list: [],
            provinces: [],
            cities: [],
            districts: [],
            detailDialogVisible: false,
            detailLoading: false,
            detailData: null,
            detailForm: {
                id: '',
                store_name: '',
                operating_state: 0,
                category_id: '',
                thumb: '',
                aptitude_imgs: [],
                province_id: '',
                city_id: '',
                district_id: '',
                address: '',
                longitude: null,
                latitude: null,
                mobile: '',
                store_introduce: '',
                business_hours_start: '',
                business_hours_end: '',
                manager_info: null,
                uid: '',
                recruiter_id: '',
                username: ''
            },
            detailRules: {
                store_name: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
                operating_state: [{ required: true, message: '请选择经营状态', trigger: 'change' }],
                category_id: [{ required: true, message: '请选择门店分类', trigger: 'change' }],
                province_id: [{ required: true, message: '请选择省份', trigger: 'change' }],
                city_id: [{ required: true, message: '请选择城市', trigger: 'change' }],
                district_id: [{ required: true, message: '请选择区县', trigger: 'change' }],
                address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
                mobile: [{ required: true, message: '请输入店铺电话', trigger: 'blur' }],
                store_introduce: [{ required: true, message: '请输入门店介绍', trigger: 'blur' }],
                uid: [{ required: true, message: '请选择门店店长', trigger: 'change' }],
                business_hours: [{ validator: (rule, value, callback) => {
                    if (!this.detailForm.business_hours_start || !this.detailForm.business_hours_end) {
                        callback(new Error('请选择营业时间'));
                    } else {
                        callback();
                    }
                }, trigger: 'change' }]
            },
            saveLoading: false,
            uploadUrl: '/admin/upload',
            aptitudeFileList: [],
            categoryOptions: [],
            categoryNameMap: {},
            provinceOptions: [],
            cityOptions: [],
            districtOptions: [],
            // 地图选择坐标
            mapDialogVisible: false,
            mapInstance: null,
            mapMarker: null,
            mapKeyword: '',
            // 二维码相关
            qrCodeDialogVisible: false,
            currentQRCode: '',
            currentStore: null,
            
            // 修改密码相关
            passwordDialogVisible: false,
            passwordLoading: false,
            passwordForm: {
                id: '',
                new_password: '',
                confirm_password: ''
            },
            
            // 核销员清单相关
            clerksDialogVisible: false,
            clerksLoading: false,
            clerksList: [],
            currentStoreId: '',
            clerksSearchForm: {
                clerk_id: '',
                realname: '',
                mobile: '',
                status: ''
            },
            
            // 置换分组相关
            groupDialogVisible: false,
            groupsLoading: false,
            groupsList: [],
            selectedGroupId: '',
            
            // 置换分组设置相关
            switchGroupsDialogVisible: false,
            switchGroupsLoading: false,
            switchGroups: [],
            selectedSwitchGroupId: null,
            groupProperties: [],
            storeGroupRelations: [],
            currentStoreForSwitch: null,
            switchGroupForm: {
                relations: []
            },
            // 店长选择
            managerDialogVisible: false,
            managerKeyword: '',
            managerLoading: false,
            managerList: []
        }
    },
    mounted() {
        this.loadProvinces();
        this.loadCategoryOptions();
        this.fetchList();
    },
    computed: {
        aptitudePreviewList() {
            return this.aptitudeFileList
                .map(file => file && (file.url || file.response?.data?.url))
                .filter(url => !!url);
        }
    },
    methods: {
        // 拉取列表
        async fetchList() {
            this.loading = true;
            try {
                const params = Object.assign({}, this.searchForm, {
                    page: this.pagination.page,
                    pageSize: this.pagination.pageSize,
                });
                
                // 处理日期范围
                if (this.searchForm.date_range && this.searchForm.date_range.length === 2) {
                    params.start_date = this.searchForm.date_range[0];
                    params.end_date = this.searchForm.date_range[1];
                }
                delete params.date_range;
                
                // 过滤空值
                Object.keys(params).forEach(key => {
                    if (params[key] === '' || params[key] === null || params[key] === undefined) {
                        delete params[key];
                    }
                });
                
                const response = await storeApi.getList(params);
                if (response && response.status === 'success') {
                    this.list = response.data.list || [];
                    if (response.data.pagination) {
                        this.pagination = response.data.pagination;
                    }
                } else {
                    this.$message.error(response.message || '加载列表失败');
                }
            } catch (e) {
                console.error('fetch list error', e);
                this.$message.error('加载列表失败');
            } finally {
                this.loading = false;
            }
        },
        
        // 加载省份数据
        async loadProvinces() {
            try {
                const response = await storeApi.getProvinces();
                console.log(response,'response')
                if (response && response.status === 'success') {
                    this.provinces = response.data || [];
                } else {
                    console.error('加载省份数据失败');
                    this.provinces = [];
                }
            } catch (e) {
                console.error('load provinces error', e);
                this.provinces = [];
            }
        },

        // 省份改变时加载城市
        async onProvinceChange(provinceId) {
            this.searchForm.city_id = '';
            this.searchForm.district_id = '';
            this.cities = [];
            this.districts = [];
            
            if (provinceId) {
                try {
                    const response = await storeApi.getCities(provinceId);
                    console.log(response,'response')
                    if (response && response.status === 'success') {
                        this.cities = response.data || [];
                    } else {
                        console.error('加载城市数据失败');
                        this.cities = [];
                    }
                } catch (e) {
                    console.error('load cities error', e);
                    this.cities = [];
                }
            }
        },

        // 城市改变时加载区县
        async onCityChange(cityId) {
            this.searchForm.district_id = '';
            this.districts = [];
            
            if (cityId) {
                try {
                    const response = await storeApi.getDistricts(cityId);
                    if (response && response.status === 'success') {
                        this.districts = response.data || [];
                    } else {
                        console.error('加载区县数据失败');
                        this.districts = [];
                    }
                } catch (e) {
                    console.error('load districts error', e);
                    this.districts = [];
                }
            }
        },
        
        // 搜索
        handleSearch() {
            this.pagination.page = 1;
            this.fetchList();
        },
        
        // 重置
        handleReset() {
            this.searchForm = {
                store_name: '',
                uid: '',
                applicant_info: '',
                province_id: '',
                city_id: '',
                district_id: '',
                date_range: [],
                is_black: 0
            };
            this.cities = [];
            this.districts = [];
            this.pagination.page = 1;
            this.fetchList();
        },
        
        // 当前页改变
        handleCurrentChange(val) {
            this.pagination.page = val;
            this.fetchList();
        },
        
        // 处理下拉菜单命令
        handleCommand(command) {
            const { action, id, current } = command;
            
            switch (action) {
                case 'detail':
                    this.showDetail(id);
                    break;
                case 'password':
                    this.showPasswordDialog(id);
                    break;
                case 'blacklist':
                    this.toggleBlacklist(id, current);
                    break;
                case 'clerks':
                    this.showClerksDialog(id);
                    break;
                case 'group':
                    this.showSwitchGroupsDialog(id);
                    break;
                default:
                    console.warn('未知的操作类型:', action);
            }
        },
        
        // 更新状态
        async updateStatus(id, field, value) {
            try {
                const response = await storeApi.updateStatus({
                    id: id,
                    field: field,
                    value: value
                });
                if (response && response.status === 'success') {
                    this.$message.success(response.message || '状态更新成功');
                    this.fetchList(); // 重新加载列表
                } else {
                    this.$message.error(response.message || '状态更新失败');
                }
            } catch (error) {
                console.error('update status error', error);
                this.$message.error('状态更新失败');
            }
        },
        
        // 显示详情
        async showDetail(id) {
            this.detailDialogVisible = true;
            this.detailLoading = true;
            this.detailData = null;
            
            try {
                const response = await storeApi.getDetail(id);
                if (response && response.status === 'success') {
                    this.detailData = response.data;
                    // 填充表单数据
                    this.fillDetailForm(response.data);
                } else {
                    this.$message.error('加载详情失败');
                }
            } catch (error) {
                console.error('show detail error', error);
                this.$message.error('加载详情失败');
            } finally {
                this.detailLoading = false;
            }
        },
        
        // 填充详情表单
        fillDetailForm(data) {
            if(data.owner){
                data.owner.uid = data.owner.id;
            }
            this.detailForm = {
                id: data.id,
                store_name: data.store_name || '',
                operating_state: data.operating_state || 0,
                category_id: data.category_id || '',
                thumb: data.thumb || '',
                aptitude_imgs: data.aptitude_imgs || [],
                province_id: data.province_id || '',
                city_id: data.city_id || '',
                district_id: data.district_id || '',
                address: data.address || '',
                longitude: data.longitude || null,
                latitude: data.latitude || null,
                mobile: data.mobile || '',
                store_introduce: data.store_introduce || '',
                business_hours_start: data.business_hours_start || '',
                business_hours_end: data.business_hours_end || '',
                manager_info: data.owner || null,
                uid: (data.owner && (data.owner.uid || data.owner.id)) || data.uid || '',
                recruiter_id: data.recruiter_id || '',
                username: data.username || ''
            };
            
            // 处理资质图片文件列表
            this.aptitudeFileList = (data.aptitude_imgs || []).map((url, index) => ({
                name: `aptitude_${index}`,
                url: url
            }));
            
            // 加载相关选项数据
            this.loadCategoryOptions();
            this.loadProvinceOptions();
            if (data.province_id) {
                this.loadCityOptions(data.province_id);
            }
            if (data.city_id) {
                this.loadDistrictOptions(data.city_id);
            }

            // 若后端未返回 manager_info，但存在相关字段，进行回退构造
            if (!this.detailForm.manager_info && (data.uid || data.member_avatar || data.member_nickname)) {
                this.detailForm.manager_info = {
                    id: data.uid || '',
                    name: data.member_nickname || data.nickname || data.realname || '',
                    avatar: data.member_avatar || data.avatar || ''
                };
            }
        },
        
        // 保存门店详情
        async saveStoreDetail() {
            this.saveLoading = true;
            try {
                // 先校验
                const valid = await new Promise(resolve => {
                    this.$refs.detailFormRef.validate(v => resolve(v));
                });
                if (!valid) {
                    this.saveLoading = false;
                    return;
                }
                const formData = Object.assign({}, this.detailForm);
                // 处理资质图片
                formData.aptitude_imgs = this.aptitudeFileList.map(file => file.url);
                
                const response = await window.api.post('/admin/store/update-detail',{
                    formData
                })
                if (response && response.status === 'success') {
                    this.$message.success('保存成功');
                    this.detailDialogVisible = false;
                    this.fetchList(); // 刷新列表
                } else {
                    this.$message.error(response.message || '保存失败');
                }
            } catch (error) {
                console.error('save detail error', error);
                this.$message.error('保存失败');
            } finally {
                this.saveLoading = false;
            }
        },
        
        // 加载分类选项（优先走 storeApi，若不存在则调用固定接口），兼容字段：name/title/category_name
        async loadCategoryOptions() {
            try {
                let response;
                if (window.storeApi && typeof storeApi.getCategories === 'function') {
                    response = await storeApi.getCategories();
                }
                if (response && response.status === 'success') {
                    const raw = Array.isArray(response.data)
                        ? response.data
                        : (Array.isArray(response.data?.list) ? response.data.list : []);
                    this.categoryOptions = raw.map(item => ({
                        id: item.id,
                        name: item.name || item.title || item.category_name || ''
                    })).filter(opt => opt.id && opt.name);
                    // 构建 id=>name 映射，供列表渲染使用
                    this.categoryNameMap = this.categoryOptions.reduce((acc, cur) => {
                        acc[cur.id] = cur.name;
                        return acc;
                    }, {});
                    if (!this.categoryOptions.length) {
                        console.warn('分类数据为空，请检查 ims_yz_store_category 表或接口返回');
                    }
                } else {
                    this.categoryOptions = [];
                }
            } catch (error) {
                console.error('load categories error', error);
                this.categoryOptions = [];
            }
        },
        
        // 加载省份选项
        async loadProvinceOptions() {
            try {
                const response = await storeApi.getProvinces();
                if (response && response.status === 'success') {
                    this.provinceOptions = response.data || [];
                }
            } catch (error) {
                console.error('load provinces error', error);
            }
        },
        
        // 省份改变
        async onProvinceChange2(provinceId) {
            this.detailForm.city_id = '';
            this.detailForm.district_id = '';
            this.cityOptions = [];
            this.districtOptions = [];
            if (provinceId) {
                await this.loadCityOptions(provinceId);
            }
        },
        
        // 加载城市选项
        async loadCityOptions(provinceId) {
            try {
                const response = await storeApi.getCities(provinceId);
                if (response && response.status === 'success') {
                    this.cityOptions = response.data || [];
                }
            } catch (error) {
                console.error('load cities error', error);
            }
        },
        
        // 城市改变
        async onCityChange2(cityId) {
            this.detailForm.district_id = '';
            this.districtOptions = [];
            if (cityId) {
                await this.loadDistrictOptions(cityId);
            }
        },
        
        // 加载区县选项
        async loadDistrictOptions(cityId) {
            try {
                const response = await storeApi.getDistricts(cityId);
                if (response && response.status === 'success') {
                    this.districtOptions = response.data || [];
                }
            } catch (error) {
                console.error('load districts error', error);
            }
        },
        
        // 上传前验证
        beforeAvatarUpload(file) {
            const isImage = file && file.type && file.type.startsWith('image/');
            const isLt10M = file && file.size / 1024 / 1024 < 10;

            if (!isImage) {
                this.$message.error('只能上传图片文件!');
                return false;
            }
            if (!isLt10M) {
                this.$message.error('图片大小不能超过 10MB!');
                return false;
            }
            return true;
        },

        async handleImageUploadRequest(options) {
            const {
                file,
                data,
                action,
                onSuccess,
                onError,
                onProgress
            } = options;

            const uploadUrl = action || this.uploadUrl;
            const axiosInstance = (window && (window.axios || window.Axios)) || (typeof axios !== 'undefined' ? axios : null);

            if (!uploadUrl) {
                const error = new Error('上传地址未配置');
                onError && onError(error);
                this.$message.error(error.message);
                return;
            }

            if (!axiosInstance) {
                const error = new Error('上传组件依赖的 axios 未加载');
                onError && onError(error);
                this.$message.error(error.message);
                return;
            }

            try {
                const compressedFile = await this.compressImage(file, {
                    maxWidth: 1280,
                    maxHeight: 1280,
                    quality: 0.8
                });

                const formData = new FormData();
                if (data && typeof data === 'object') {
                    Object.keys(data).forEach(key => {
                        const value = data[key];
                        if (value !== undefined && value !== null) {
                            formData.append(key, value);
                        }
                    });
                }
                formData.append('file', compressedFile, compressedFile.name || file.name);

                const config = {
                    headers: { 'Content-Type': 'multipart/form-data' },
                    onUploadProgress: (event) => {
                        if (event.total > 0 && typeof onProgress === 'function') {
                            const percent = Math.round((event.loaded / event.total) * 100);
                            onProgress({ percent });
                        }
                    }
                };

                const response = await axiosInstance.post(uploadUrl, formData, config);
                console.log(response, 'response');
                if (typeof onSuccess === 'function') {
                    onSuccess(response, compressedFile);
                }
            } catch (error) {
                console.error('upload error', error);
                if (typeof onError === 'function') {
                    onError(error);
                }
                this.$message.error(error.message || '图片上传失败');
            }
        },

        async compressImage(file, options = {}) {
            const { maxWidth = 1280, maxHeight = 1280, quality = 0.8 } = options;

            if (!file || !file.type || !file.type.startsWith('image/') || file.type === 'image/gif') {
                return file;
            }

            return new Promise((resolve, reject) => {
                const image = new Image();
                const objectUrl = URL.createObjectURL(file);

                image.onload = () => {
                    let { width, height } = image;
                    let targetWidth = width;
                    let targetHeight = height;

                    const scale = Math.min(maxWidth / width, maxHeight / height);
                    if (scale < 1) {
                        targetWidth = Math.round(width * scale);
                        targetHeight = Math.round(height * scale);
                    }

                    const canvas = document.createElement('canvas');
                    canvas.width = targetWidth;
                    canvas.height = targetHeight;
                    const ctx = canvas.getContext('2d');
                    ctx.clearRect(0, 0, targetWidth, targetHeight);
                    ctx.drawImage(image, 0, 0, targetWidth, targetHeight);

                    const mimeType = file.type === 'image/png' ? 'image/png' : 'image/jpeg';
                    const qualityValue = mimeType === 'image/png' ? undefined : quality;

                    canvas.toBlob(
                        blob => {
                            URL.revokeObjectURL(objectUrl);
                            if (!blob) {
                                reject(new Error('图片压缩失败'));
                                return;
                            }
                            const compressedFile = new File([blob], file.name || 'upload.jpg', {
                                type: mimeType,
                                lastModified: Date.now()
                            });
                            if (file.uid) {
                                compressedFile.uid = file.uid;
                            }
                            resolve(compressedFile);
                        },
                        mimeType,
                        qualityValue
                    );
                };

                image.onerror = () => {
                    URL.revokeObjectURL(objectUrl);
                    reject(new Error('图片加载失败'));
                };

                image.src = objectUrl;
            });
        },
        
        // Logo上传成功
        handleLogoSuccess(response, file) {
            if(!response){
                return
            }
            if (response && response.status === 'success') {
                this.detailForm.thumb = response.data.url;
            } else {
                this.$message.error('上传失败');
            }
        },
        
        // 资质图片上传成功
        handleAptitudeSuccess(response, file) {
            if(!response){
                return
            }
            if (response && response.status === 'success') {
                this.aptitudeFileList.push({
                    name: file.name,
                    url: response.data.url
                });
            } else {
                this.$message.error('上传失败');
            }
        },
        
        // 资质图片删除
        handleAptitudeRemove(file, fileList) {
            this.aptitudeFileList = fileList;
        },
        // 打开地图选择器
        openMapPicker() {
            this.mapDialogVisible = true;
            this.$nextTick(() => {
                this.initMap();
            });
        },

        // 初始化地图
        initMap() {
            if (!window.BMap) {
                this.$message.warning('地图加载中，请稍后重试');
                return;
            }
            const { longitude, latitude } = this.detailForm;
            const lng = longitude || 116.413384;
            const lat = latitude || 39.910925;
            const center = new BMap.Point(lng, lat);
            this.mapInstance = new BMap.Map(this.$refs.mapContainer);
            this.mapInstance.centerAndZoom(center, 12);
            this.mapInstance.enableScrollWheelZoom();

            this.mapMarker = new BMap.Marker(center);
            this.mapMarker.enableDragging();
            this.mapInstance.addOverlay(this.mapMarker);

            this.mapMarker.addEventListener('dragend', (e) => {
                const p = e.point;
                this.detailForm.longitude = Number(p.lng.toFixed(6));
                this.detailForm.latitude = Number(p.lat.toFixed(6));
            });

            this.mapInstance.addEventListener('click', (e) => {
                if (!e.point) return;
                const p = e.point;
                this.mapMarker.setPosition(p);
                this.detailForm.longitude = Number(p.lng.toFixed(6));
                this.detailForm.latitude = Number(p.lat.toFixed(6));
            });
        },

        // 地点搜索
        searchMap() {
            if (!this.mapInstance || !this.mapKeyword) return;
            const local = new BMap.LocalSearch(this.mapInstance, {
                onSearchComplete: (results) => {
                    if (local.getStatus() === BMAP_STATUS_SUCCESS) {
                        const first = results.getPoi(0);
                        if (first && first.point) {
                            this.mapInstance.centerAndZoom(first.point, 16);
                            this.mapMarker.setPosition(first.point);
                            this.detailForm.longitude = Number(first.point.lng.toFixed(6));
                            this.detailForm.latitude = Number(first.point.lat.toFixed(6));
                        }
                    }
                }
            });
            local.search(this.mapKeyword);
        },

        // 确认选择
        confirmMapPoint() {
            this.mapDialogVisible = false;
        },
        
        // 打开店长选择弹窗
        openManagerDialog() {
            this.managerKeyword = '';
            this.managerList = [];
            this.managerDialogVisible = true;
        },
        // 搜索店长
        async searchManagers() {
            this.managerLoading = true;
            try {
                const res = await fetch('/admin/store/search-managers?keyword=' + encodeURIComponent(this.managerKeyword || ''), { credentials: 'same-origin' });
                const data = await res.json();
                if (data && data.status === 'success') {
                    this.managerList = data.data || [];
                } else {
                    this.$message.error(data.message || '搜索失败');
                }
            } catch (e) {
                console.error('search managers error', e);
                this.$message.error('搜索失败');
            } finally {
                this.managerLoading = false;
            }
        },
        // 选择店长
        chooseManager(row) {
            this.detailForm.manager_info = {
                id: row.uid,
                name: row.name || row.nickname || '',
                avatar: row.avatar || ''
            };
            this.detailForm.uid = row.uid; // 若后端需要保存 uid，可一并带上
            this.managerDialogVisible = false;
        },

        // 清空店长选择
        clearManager() {
            this.detailForm.manager_info = null;
            this.detailForm.uid = '';
        },
        showPasswordDialog2(){
            this.showPasswordDialog(this.detailForm.id);
        },
        // 显示修改密码弹窗
        showPasswordDialog(id) {
            // 如果传入了id参数，使用传入的id（从操作菜单调用）
            // 如果没有传入id，使用详情表单的id（从详情弹窗调用）
            const storeId = id || this.detailForm.id;
            
            this.passwordForm = {
                id: storeId,
                new_password: '',
                confirm_password: ''
            };
            this.passwordDialogVisible = true;
        },
        
        // 获取经营状态类型
        getOperatingStateType(state) {
            return state === 0 ? 'success' : 'warning';
        },
        
        // 获取显示状态类型
        getHideType(hide) {
            return hide === 0 ? 'success' : 'danger';
        },
        
        // 获取黑名单状态类型
        getBlackType(black) {
            return black === 0 ? 'success' : 'danger';
        },
        
        // 获取有效期状态类型
        getValidityType(validity) {
            return validity === 0 ? 'success' : 'danger';
        },
        
        // 查看二维码
        async viewQRCode(store, qrType) {
            this.currentQRCode=''
            this.currentStore = store;
            this.qrCodeDialogVisible = true;
            
            // 如果是收款二维码，调用后端API获取
            if (qrType === 'collect_money_url') {
                try {
                    const response = await storeApi.getQrCode(store.id, 1); // 1表示公众号二维码
                    if (response && response.result === 1) {
                        this.currentQRCode = response.data || '';
                    } else {
                        this.$message.error(response.msg || '获取二维码失败');
                        this.currentQRCode = '';
                    }
                } catch (error) {
                    console.error('get qr code error', error);
                    this.$message.error('获取二维码失败');
                    this.currentQRCode = '';
                }
            } else {
                this.currentQRCode = store[qrType] || '';
            }
        },
        
        // 切换黑名单状态
        async toggleBlacklist(id, current) {
            const action = current ? '移出黑名单' : '加入黑名单';
            try {
                await this.$confirm(`确定要${action}吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
                
                const response = await storeApi.updateStatus({
                    id: id,
                    field: 'is_black',
                    value: current ? 0 : 1
                });
                
                if (response && response.status === 'success') {
                    this.$message.success(response.message || `${action}成功`);
                    this.fetchList();
                } else {
                    this.$message.error(response.message || `${action}失败`);
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('toggle blacklist error', error);
                    this.$message.error(`${action}失败`);
                }
            }
        },
        
        // 切换推荐状态
        async toggleRecommend(store) {
            try {
                const response = await storeApi.updateStatus({
                    id: store.id,
                    field: 'is_recommend',
                    value: store.is_recommend
                });
                
                if (response && response.status === 'success') {
                    this.$message.success(store.is_recommend ? '已设为推荐' : '已取消推荐');
                } else {
                    // 如果失败，恢复原状态
                    store.is_recommend = store.is_recommend === 1 ? 0 : 1;
                    this.$message.error(response.message || '操作失败');
                }
            } catch (error) {
                // 如果失败，恢复原状态
                store.is_recommend = store.is_recommend === 1 ? 0 : 1;
                console.error('toggle recommend error', error);
                this.$message.error('操作失败');
            }
        },
        
        // 显示核销员清单弹窗
        showClerksDialog(id) {
            this.currentStoreId = id;
            this.clerksDialogVisible = true;
            this.loadClerks(id);
        },
        
        // 显示置换分组弹窗
        async showSwitchGroupsDialog(id) {
            this.currentStoreForSwitch = this.list.find(store => store.id === id);
            this.switchGroupsDialogVisible = true;
            this.switchGroupsLoading = true;
            
            try {
                // 加载置换分组列表
                let data= await this.getSwitchGroups({
                    store_id:id
                });
                this.switchGroups = data.groups
                
                // 重置选择状态
                this.selectedSwitchGroupId =data.group_id|| null;
                if(data.group_id){
                    this.onSwitchGroupChange(data.group_id);
                }
                this.groupProperties = [];
                this.storeGroupRelations = [];
            } catch (error) {
                console.error('show switch groups dialog error', error);
            } finally {
                this.switchGroupsLoading = false;
            }
        },
        
        // 加载核销员列表
        async loadClerks(storeId, searchParams = {}) {
            this.clerksLoading = true;
            try {
                const params = Object.assign({}, searchParams);
                // 过滤空值
                Object.keys(params).forEach(key => {
                    if (params[key] === '' || params[key] === null || params[key] === undefined) {
                        delete params[key];
                    }
                });
                
                const response = await storeApi.getClerks(storeId, params);
                if (response && response.status === 'success') {
                    this.clerksList = response.data || [];
                } else {
                    this.$message.error('加载核销员列表失败');
                    this.clerksList = [];
                }
            } catch (error) {
                console.error('load clerks error', error);
                this.$message.error('加载核销员列表失败');
                this.clerksList = [];
            } finally {
                this.clerksLoading = false;
            }
        },
        
        // 搜索核销员
        searchClerks() {
            this.loadClerks(this.currentStoreId, this.clerksSearchForm);
        },
        
        // 重置核销员搜索
        resetClerksSearch() {
            this.clerksSearchForm = {
                clerk_id: '',
                realname: '',
                mobile: '',
                status: ''
            };
            this.loadClerks(this.currentStoreId);
        },
        

        
        // 修改密码
        async updatePassword() {
            if (!this.passwordForm.new_password) {
                this.$message.error('请输入新密码');
                return;
            }
            if (this.passwordForm.new_password !== this.passwordForm.confirm_password) {
                this.$message.error('两次输入的密码不一致');
                return;
            }
            
            this.passwordLoading = true;
            try {
                const response = await storeApi.updatePassword({
                    id: this.passwordForm.id,
                    new_password: this.passwordForm.new_password
                });
                
                if (response && response.status === 'success') {
                    this.$message.success('密码修改成功');
                    this.passwordDialogVisible = false;
                } else {
                    this.$message.error(response.message || '密码修改失败');
                }
            } catch (error) {
                console.error('update password error', error);
                this.$message.error('密码修改失败');
            } finally {
                this.passwordLoading = false;
            }
        },
        
        // 置换分组选择变化
        async onSwitchGroupChange(groupId) {
            if (!groupId) {
                this.groupProperties = [];
                this.storeGroupRelations = [];
                return;
            }
            
            this.switchGroupsLoading = true;
            try {
                // 获取分组属性
                const properties = await this.getGroupProperties(groupId);
                
                // 获取门店分组关系
                const relations = await this.getStoreGroupRelations(this.currentStoreForSwitch.id, groupId);
                
                // 合并数据，设置默认值
                this.groupProperties = properties.map(prop => {
                    const relation = relations.find(rel => rel.group_propertie_id === prop.id);
                    return {
                        ...prop,
                        settlement_num: relation ? parseFloat(relation.settlement_num) : 0,
                        is_enabled: relation ? Boolean(relation.state) : false
                    };
                });
                
                this.storeGroupRelations = relations;
            } catch (error) {
                console.error('on switch group change error', error);
            } finally {
                this.switchGroupsLoading = false;
            }
        },
        
        // 保存置换分组设置
        async saveSwitchGroupSettings() {
            if (!this.selectedSwitchGroupId) {
                this.$message.error('请选择置换分组');
                return;
            }
            
            this.switchGroupsLoading = true;
            try {
                // 构建更新数据
                const updateData = {
                    group_id: this.selectedSwitchGroupId,
                    relations: this.groupProperties.map(prop => ({
                        group_propertie_id: prop.id,
                        settlement_num: prop.settlement_num || 0,
                        state: prop.is_enabled ? 1 : 0
                    }))
                };
                
                const success = await this.updateStoreGroupRelations(this.currentStoreForSwitch.id, updateData);
                
                if (success) {
                    this.switchGroupsDialogVisible = false;
                    this.fetchList(); // 重新加载列表数据
                }
            } catch (error) {
                console.error('save switch group settings error', error);
                this.$message.error('保存置换分组设置失败');
            } finally {
                this.switchGroupsLoading = false;
            }
        },
        
        // 获取置换分组列表
        async getSwitchGroups(data) {
            try {
                const response = await storeApi.getSwitchGroups(data);
                if (response && response.status === 'success') {
                    return response.data || {};
                } else {
                    this.$message.error('获取置换分组列表失败');
                    return [];
                }
            } catch (error) {
                console.error('get switch groups error', error);
                this.$message.error('获取置换分组列表失败');
                return [];
            }
        },
        
        // 获取分组属性
        async getGroupProperties(groupId) {
            try {
                const response = await storeApi.getGroupProperties(groupId);
                if (response && response.status === 'success') {
                    return response.data || [];
                } else {
                    this.$message.error('获取分组属性失败');
                    return [];
                }
            } catch (error) {
                console.error('get group properties error', error);
                this.$message.error('获取分组属性失败');
                return [];
            }
        },
        
        // 获取门店分组关系
        async getStoreGroupRelations(storeId, groupId) {
            try {
                const response = await storeApi.getStoreGroupRelations(storeId, groupId);
                if (response && response.status === 'success') {
                    return response.data || [];
                } else {
                    this.$message.error('获取门店分组关系失败');
                    return [];
                }
            } catch (error) {
                console.error('get store group relations error', error);
                this.$message.error('获取门店分组关系失败');
                return [];
            }
        },
        
        // 更新门店分组关系
        async updateStoreGroupRelations(storeId, data) {
            try {
                const response = await storeApi.updateStoreGroupRelations(storeId, data);
                if (response && response.status === 'success') {
                    this.$message.success('门店分组关系更新成功');
                    return true;
                } else {
                    this.$message.error(response.message || '门店分组关系更新失败');
                    return false;
                }
            } catch (error) {
                console.error('update store group relations error', error);
                this.$message.error('门店分组关系更新失败');
                return false;
            }
        },
        
        // 切换核销员状态
        async toggleClerkStatus(clerk) {
            const action = clerk.status == 10 ? '停用' : '启用';
            try {
                await this.$confirm(`确定要${action}该核销员吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
                
                const newStatus = clerk.status === 10 ? 20 : 10;
                const response = await storeApi.updateClerkStatus({
                    id: clerk.id,
                    status: newStatus
                });
                
                if (response && response.status === 'success') {
                    this.$message.success(`${action}成功`);
                    clerk.status = newStatus; // 更新本地状态
                } else {
                    this.$message.error(response.message || `${action}失败`);
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('toggle clerk status error', error);
                    this.$message.error(`${action}失败`);
                }
            }
        },
        
        // 下载二维码
        async downloadQRCode(store, qrType) {
            let qrUrl = '';
            
            // 如果是收款二维码，调用后端API获取
            if (qrType === 'collect_money_url') {
                try {
                    const response = await storeApi.getQrCode(store.id, 1); // 1表示公众号二维码
                    if (response && response.result === 1) {
                        qrUrl = response.data || '';
                    } else {
                        this.$message.error(response.msg || '获取二维码失败');
                        return;
                    }
                } catch (error) {
                    console.error('get qr code error', error);
                    this.$message.error('获取二维码失败');
                    return;
                }
            } else {
                qrUrl = store[qrType];
            }
            
            if (!qrUrl) {
                this.$message.warning('暂无二维码');
                return;
            }
            
            // 创建下载链接
            const link = document.createElement('a');
            link.href = qrUrl;
            link.download = `${store.store_name}_${qrType}.png`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },
        
        // 下载当前二维码
        downloadCurrentQRCode() {
            if (this.currentStore && this.currentQRCode) {
                this.downloadQRCode(this.currentStore, 'collect_money_url');
            }
        }
    }
});
</script>

<style>
.page-header {
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 20px;
}

.search-form .el-form-item {
    margin-bottom: 10px;
}

.applicant-info {
    display: flex;
    align-items: center;
}

.applicant-info .el-avatar {
    flex-shrink: 0;
}

.applicant-info .el-avatar img {
    object-fit: cover;
    width: 100%;
    height: 100%;
}

.applicant-info .info-text {
    margin-left: 8px;
}

.applicant-info .name {
    font-weight: 500;
    font-size: 14px;
}

.applicant-info .id {
    font-size: 12px;
    color: #909399;
}

.store-name {
    font-weight: 500;
    margin-bottom: 2px;
}

.address {
    font-size: 12px;
    margin-bottom: 2px;
}

.category {
    font-size: 12px;
}

.pagination-wrapper {
    display: flex;
    justify-content: center;
}

.text-muted {
    color: #909399;
}

.text-info {
    color: #409EFF;
}

.ml-1 {
    margin-left: 4px;
}

.ml-2 {
    margin-left: 8px;
}

.mr-2 {
    margin-right: 8px;
}

.mb-4 {
    margin-bottom: 24px;
}

.mb-3 {
    margin-bottom: 16px;
}

.mt-1 {
    margin-top: 4px;
}

.mt-2 {
    margin-top: 8px;
}

.mt-3 {
    margin-top: 16px;
}

.form-text {
    font-size: 12px;
}

/* 详情页面样式 */
.detail-content .detail-item {
    margin-bottom: 12px;
}

.detail-content .detail-item label {
    font-weight: 500;
    color: #606266;
    margin-right: 8px;
    min-width: 80px;
    display: inline-block;
}

.detail-content .detail-item span {
    color: #303133;
}

.detail-content .el-card {
    margin-bottom: 16px;
}

.detail-content .el-card:last-child {
    margin-bottom: 0;
}

.detail-content .el-card__header {
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
}

.detail-content .el-card__header span {
    font-weight: 500;
    color: #303133;
}

.detail-content .el-card__header i {
    margin-right: 6px;
    color: #409EFF;
}

.text-center {
    text-align: center;
}

/* 门店信息样式 */
.store-info {
    display: flex;
    align-items: center;
}

.store-thumb {
    margin-right: 12px;
}

.store-image {
    width: 40px;
    height: 40px;
    border-radius: 4px;
    object-fit: contain;
    background-color: #f5f5f5;
}

.store-details {
    flex: 1;
}

.store-name {
    font-weight: 500;
    margin-bottom: 2px;
}

.store-address {
    font-size: 12px;
    color: #909399;
}

/* 二维码操作样式 */
.qr-code-actions {
    display: flex;
    gap: 8px;
}

/* 上传组件样式 */
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 96px;
    height: 96px;
    line-height: 96px;
    text-align: center;
}

.avatar {
    width: 96px;
    height: 96px;
    display: block;
    border-radius: 4px;
    object-fit: cover;
}
.avatar.is-clickable {
    cursor: pointer;
}
.form-helper {
    margin-top: 6px;
}

/* 表单样式 */
.detail-content .el-form-item {
    margin-bottom: 18px;
}

.detail-content .el-card {
    margin-bottom: 20px;
}

.detail-content .el-card__header {
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
}

.detail-content .el-card__header span {
    font-weight: 500;
    color: #303133;
}

.detail-content .el-card__header i {
    margin-right: 6px;
    color: #409EFF;
}

/* 管理人员信息样式 */
.manager-info {
    display: flex;
    align-items: center;
    padding: 12px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #fafafa;
}

.manager-avatar {
    margin-right: 12px;
}

.manager-details {
    flex: 1;
}

.manager-name {
    font-weight: 500;
    font-size: 14px;
    color: #303133;
    margin-bottom: 4px;
}

.manager-id {
    font-size: 12px;
    color: #909399;
}

.manager-actions {
    margin-left: 12px;
}

.no-manager {
    padding: 20px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    background-color: #fafafa;
}

/* 密码信息样式 */
.password-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #f5f7fa;
}

.password-mask {
    font-family: monospace;
    font-size: 14px;
    color: #606266;
    letter-spacing: 2px;
}

/* 营业时间样式 */
.el-time-picker {
    width: 100%;
}

.image-preview-list {
    display: inline-flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 6px;
}
.image-preview-list .preview-thumbnail,
.image-preview-list .avatar {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
    object-fit: cover;
}

</style>